package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.user.api.UserApi;
import com.leyou.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * description: 授权业务
 * @author 朱正磊
 * @date 2021-04-18 11:33:36
 */
@Slf4j
@Service
public class AuthService {

    @Resource
    private UserApi userApi;

    @Resource
    private JwtProperties jwtProperties;

    /**
     * description: 用户登录
     * @author 朱正磊
     * @date 2021-04-18 11:38:48
     * @param username 用户名
     * @param password 密码
     * @return 返回JWT
     */
    public String login(String username, String password) {
        try {
            // 1、校验用户名和密码
            User user = userApi.queryUserByUsernameAndPassword(username, password);

            // 2、生成token并返回
            return JwtUtils.generateToken(new UserInfo(user.getId(), username),
                    jwtProperties.getPrivateKey(), jwtProperties.getExpire());
        } catch (Exception e) {
            log.error("【授权中心】用户名或密码有误，用户名称：{}", username, e);
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
    }

}
